package src

import (
	"fmt"
	"encoding/json"
	"net/http"	
)

type HotWatParas struct {
   NotifyBefore string `json:"notify_before"`
}

type Subscription struct {
	Type string `json:"subscription_type"`
	Channels map[string]bool `json:"channels"`
	Params interface {} `json:"params"`
}

type Subscriptions struct {
	Subscrs []Subscription `json:"subscriptions"`
}

func (s *Subscriptions) fill(body []byte) {
	err := json.Unmarshal(body, s)
	if err!=nil {
		panic("unmarchalling subscriptions error")
	}
}

func getSubscrHandler(w http.ResponseWriter, r *http.Request) {
	emp, _ := ParseParams(r)
	var session *string = nil
	if emp.Auth !=nil {
		session = emp.Auth.Session
	}
	
	var response Response
	if (session==nil){
		response = Response{ session, 403, "Unauthorized", ""} 
	} else	{
		response = Response{ session, 0, "", getSubscr()} 
	}
	
	obj,_ := json.Marshal(response)
	fmt.Fprint(w, string(obj))
}

func getSubscr() (subs []interface{}){
	channels := make(map[string]bool)
	channels["sms"] = true
	channels["email"] = false
	channels["push"] = true
	params := &HotWatParas{"week"}
	subs = append(subs, Subscription{"offences", channels,nil})
	subs = append(subs, Subscription{"FSSP", channels,nil})
	subs = append(subs, Subscription{"hotwater_off", channels, params})
	subs = append(subs, Subscription{"evacuation", channels, nil})
	subs = append(subs, Subscription{"news", channels, nil})
	subs = append(subs, Subscription{"gku", channels, nil})	
	subs = append(subs, Subscription{"road_info", channels, getRoadInfoParams()})	
		
	return
}

func getRoadInfoParams() (params map[string]interface{}){
	params = make(map[string]interface{})
    
    var groups []RoadGroup
    var roads []Road
    roads = append(roads,Road{1,"Ярославское шоссе", false})
    roads = append(roads,Road{2,"Щелковское шоссе", true})
    roads = append(roads,Road{3,"Боровское шоссе", true})
    groups = append(groups,RoadGroup{"Радиальные", roads})
    var roads2 []Road
    roads2 = append(roads2,Road{5,"МКАД север", false})
	roads2 = append(roads2,Road{8,"МКАД юг", false})
	roads2 = append(roads2,Road{6,"МКАД запад", false})
	roads2 = append(roads2,Road{12,"МКАД восток", false})
		
    groups = append(groups,RoadGroup{"Кольцевые", roads2})
    params["groups"] = groups
	return 
}

func updateSubscrHandler(w http.ResponseWriter, r *http.Request) {
	emp, body := ParseParams(r)
	var session *string = nil
	if emp.Auth !=nil {
		session = emp.Auth.Session
	}
	var subs Subscriptions 
	subs.fill(body)
		
	var response Response
	if (session==nil){
		response = Response{ session, 403, "Unauthorized", ""} 
	} else if(len(subs.Subscrs)==0){
		response = Response{ session, 1102, "Pass subscriptions please", ""} 
	} else	{
		response = Response{ session, 0, "", "OK"} 
	}
	
	obj,_ := json.Marshal(response)
	fmt.Fprint(w, string(obj))
}